package cn.hackcloud.demo.dubbo.service;

import com.alibaba.csp.sentinel.datasource.ReadableDataSource;
import com.alibaba.csp.sentinel.datasource.zookeeper.ZookeeperDataSource;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class SentinelRuleService implements InitializingBean {
    public static final String ZOOKEEPER_ADDRESS = "127.0.0.1:2181";
    public static final String ZOOKEEPER_PATH = "/FLOW";

    public static void main(String[] args) {
        loadRules();
    }

    private static void loadRules() {
        ReadableDataSource<String, List<FlowRule>> flowRuleDataSource = new ZookeeperDataSource<>(ZOOKEEPER_ADDRESS, ZOOKEEPER_PATH,
                source -> JSON.parseObject(source, new TypeReference<List<FlowRule>>() {
                }));
        System.out.println(JSON.toJSONString(flowRuleDataSource));
        FlowRuleManager.register2Property(flowRuleDataSource.getProperty());
    }

    @Override
    public void afterPropertiesSet() {
        loadRules();
        System.out.println("加载规则成功！");
    }
}
